<template>
  <ElDrawer v-model="opened" title="年度人口列表" size="50%" destroy-on-close>
    <div v-show="operator === 'list'">
      <ProTable ref="proTableRef" row-key="id" title="列表" :columns="columns" :request-api="loadTable" highlight-current-row>
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <ElButton type="primary" :icon="CirclePlus" @click="onAddClicked">新增</ElButton>
        </template>
        <!-- 账户操作 -->
        <template #operation="scope">
          <ElButton type="warning" link :icon="EditPen" @click="onEditClicked(scope.row)">编辑</ElButton>
          <ElButton type="danger" link :icon="Delete" @click="onDeleteClicked(scope.row)">删除</ElButton>
        </template>
      </ProTable>
    </div>
    <div v-show="operator !== 'list'">
      <div style="width: 100%; margin-left: 200px">
        <ElForm :model="form" :rules="rules" ref="formRef" status-icon>
          <ElFormItem label="年份" :label-width="labelWidth" prop="year">
            <el-date-picker v-model="form.year" type="year" value-format="YYYY" format="YYYY" style="width: 40%" />
          </ElFormItem>
          <ElFormItem label="户籍人口" :label-width="labelWidth" prop="registeredPopulation">
            <ElInputNumber v-model="form.registeredPopulation" style="width: 40%" />
          </ElFormItem>
          <ElFormItem label="常住人口" :label-width="labelWidth" prop="permanentPopulation">
            <ElInputNumber v-model="form.permanentPopulation" style="width: 40%" />
          </ElFormItem>
          <ElFormItem label="劳动力" :label-width="labelWidth" prop="labourForce">
            <ElInputNumber v-model="form.labourForce" style="width: 40%" />
          </ElFormItem>
        </ElForm>
        <div style="width: 400px; text-align: center">
          <ElButton type="primary" @click="onSaveClicked">保存</ElButton>
          <ElButton @click="onCancelClicked">返回</ElButton>
        </div>
      </div>
    </div>
  </ElDrawer>
</template>

<script setup lang="ts">
import { ref, reactive, unref } from 'vue'
import { CirclePlus, Delete, EditPen } from '@element-plus/icons-vue'
import ProTable from '@/components/ProTable/index.vue'
import { ColumnProps, ProTableInstance } from '@/components/ProTable/interface'
import {
  VillagePerson,
  pageVillagePerson,
  removeVillagePerson,
  getVillagePersonDetail,
  saveOrUpdateVillagePerson
} from '@api/tby/community/villagePerson'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import { validateInteger } from '@/api/modules/tby/common/common'

const opened = ref(false)
const operator = ref<string>('list')
const formRef = ref<FormInstance>()
const form = ref<Partial<VillagePerson.Form>>({})
const labelWidth = 100
const villageId = ref<number>(0)

const open = async (id: number) => {
  villageId.value = id
  opened.value = true
}

const close = () => {
  opened.value = false
}

const proTableRef = ref<ProTableInstance>()

function getIndex(index: number) {
  const { current, size } = proTableRef.value!.pageable
  return (current - 1) * size + index + 1
}

// 表格列
const columns = reactive<ColumnProps<VillagePerson.Record>[]>([
  { type: 'index', label: '序号', width: 60, index: getIndex },
  { prop: 'year', label: '年份', align: 'center' },
  { prop: 'registeredPopulation', label: '户籍人口', align: 'center' },
  { prop: 'permanentPopulation', label: '常驻人口', align: 'center' },
  { prop: 'labourForce', label: '劳动力', align: 'center' },
  { prop: 'operation', label: '操作', fixed: 'right', width: 180 }
])

const loadTable = (query: VillagePerson.Query) => {
  query.villageId = villageId.value
  query.order = 'year desc'
  return pageVillagePerson(query)
}

// 添加
const onAddClicked = () => {
  operator.value = 'add'
}

// 修改
const onEditClicked = async (row: any) => {
  operator.value = 'edit'
  let { data } = await getVillagePersonDetail(row.id)
  form.value = data
  console.log(form.value.year)
}

// 删除
const onDeleteClicked = (row: any) => {
  ElMessageBox.confirm('是否删除数据?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeVillagePerson(row.id).then(response => {
      console.log(response)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      proTableRef.value?.getTableList()
    })
  })
}

const rules = reactive<FormRules>({
  year: [{ required: true, message: '年份不能为空', trigger: 'blur' }],
  registeredPopulation: [
    { required: true, message: '户籍人口不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: 'blur' }
  ],
  permanentPopulation: [
    { required: true, message: '常住人口不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: 'blur' }
  ],
  labourForce: [
    { required: true, message: '劳动力不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: 'blur' }
  ]
})

const onSaveClicked = () => {
  if (!formRef.value) {
    return
  }
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    formData.villageId = villageId.value
    saveOrUpdateVillagePerson(formData).then(() => {
      onCancelClicked()
      proTableRef.value?.getTableList()
    })
  })
}

const onCancelClicked = () => {
  operator.value = 'list'
}

defineExpose({
  open,
  close
})
</script>
